package com.sanyue.codingsettlement.manager;

import com.sanyue.codingsettlement.constant.AISystemMessage;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import com.zhipu.oapi.service.v4.model.ModelApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Guan
 **/
@Service
public class AiManager {

    @Resource
    private ClientV4 client;


    /**
     * 同步调用ai
     * @param systemMessage 系统预设
     * @param userMessage 用户预设
     * @return
     */
    public String aiResponse(String systemMessage, String userMessage){
        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage chatSystemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), systemMessage);
        ChatMessage chatUserMessage = new ChatMessage(ChatMessageRole.USER.value(), userMessage);
        // 注意：系统预设一定要在用户预设之前
        if(!StringUtils.isBlank(systemMessage)){
            messages.add(chatSystemMessage);
        }
        messages.add(chatUserMessage);
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .build();
        ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest);
        return invokeModelApiResp.getData().getChoices().get(0).getMessage().getContent().toString();
    }


    /**
     * 同步调用ai 封装，输入用户输入即可（图表分析）
     * @param userMessage 用户预设
     * @return
     */
    public String aiResponse(String userMessage){

        return aiResponse(AISystemMessage.AI_GEN_CHART_SYSTEM_MESSAGE,userMessage);
    }


    /**
     * 同步调用ai 封装，输入用户输入即可（应用题目生成）
     * @param userMessage 用户预设
     * @return
     */
    public String getQuestionByAiResponse(String userMessage){

        return aiResponse(AISystemMessage.AI_GEN_QUESTION_SYSTEM_MESSAGE,userMessage);
    }


    /**
     * 同步调用ai 封装，输入用户输入即可（题目判题结果生成）
     * @param userMessage 用户预设
     * @return
     */
    public String getScoringResultByAiResponse(String userMessage){

        return aiResponse(AISystemMessage.AI_GEN_SCORING_RESULT_SYSTEM_MESSAGE,userMessage);
    }


}
